//
//  HomeViewModel.swift
//  JKWeiBo
//
//  Created by 王冲 on 2017/12/3.
//  Copyright © 2017年 希爱欧科技有限公司. All rights reserved.
//

import UIKit
import SDWebImage
class HomeViewModel: NSObject {
     // 微博创建的时间
     var created_at: String?
     {
        didSet{

            //created_at = "Sun Dec 1 14:52:59 +0800 2017"
            // 1.将字符串转化为时间
//            let createdate = NSDate.dateWithStr(time: created_at!)
//            // 2.获取格式化之后的时间字符串
//            created_at = createdate.descDate
//
            // "Sun Dec 1 14:52:59 +0800 2017" 字符串的转化
            created_at = NSDate.createdateWithStr(time: created_at!) as String
        }
     }
     // 微博ID
     var id: Int = 0
     // 微博信息内容
     var text: String?
     // 微博来源
     var source: String?
     {
        didSet{
            
            if let str = source
            {
                if (str as NSString).length > 0
                {
                    
                    // 1.获取开始截取的位置
                    let startLocation = (str as NSString).range(of: ">").location + 1
                    
                    // 2.获取截取的长度
                    let length = (str as NSString).range(of: "<", options: NSString.CompareOptions.backwards).location - startLocation
                    
                    // 3.截取字符串
                    source = "来自" + (str as NSString).substring(with: NSRange(location: startLocation, length: length))
                }
            }
        }
    }
    // 微博配图数组
    var pic_urls: [[String: AnyObject]]?
    {
        didSet{
            // 1.初始化数组
            storedPic_urls = [NSURL]()
            storedLargePic_urls = [NSURL]()
            for dict in pic_urls! {
                
                if let urlStr = dict["thumbnail_pic"] as? String {
                
                    // 1.将字符串转化为url保存到数组中
                    storedPic_urls?.append(NSURL(string: urlStr)!)
                    // 2.处理微博配图的大图数组
                    let largeUrlStr = urlStr.replacingOccurrences(of: "thumbnail", with: "large")
                    storedLargePic_urls?.append(NSURL(string: largeUrlStr)!)
                }
            }
            
            print("数量=\(String(describing: storedPic_urls?.count)) url数组 =\(String(describing: storedPic_urls)) ")
        }
    }
    
    // 微博配图数组Url
    var storedPic_urls: [NSURL]?
    // 微博配图数组大图的Url
    var storedLargePic_urls: [NSURL]?
    
    // user 字段里面的值
    var user: HomeUserModel?
    
    // 转发微博的数据
    var retweeted_status: HomeViewModel?

    // 如果有转发，原创就没有配图
    // 定义一个计算属性，用于返回原创获取转发配图的url数组
    var pictureURLS: [NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedPic_urls : storedPic_urls
    }
    
    // 定义一个计算属性，用于返回原创获取转发配图的大图url数组
    var largePictureURLS: [NSURL]?
    {
        return retweeted_status != nil ? retweeted_status?.storedLargePic_urls : storedLargePic_urls
    }
    
    
    class func loadStause(more_ID: Int,finshed: @escaping (_ models:[HomeViewModel]?,_ error:Error?)->()){
        
        let account = UserAccount.loadAccount()
        // 1.定义路径
        let path = "2/statuses/home_timeline.json"
        // 2.封装参数
        var params = ["access_token":account?.access_token]
        
        // 下拉刷新
        if more_ID == 0
        {
            
        }
        
        // 上拉刷新
        if more_ID > 0
        {
            let more_IDD: Int = more_ID
            params["max_id"] = "\(more_IDD - 1)"
        }
        
        NetworkTools.shareNetworkTools().get(path, parameters: params, progress: nil, success: { (_, JSON) in
            
            //print(JSON!)
            
            /*
               1.取出Stause key对应的数组(存储的都是字典)
               2.遍历数组将字典转化为模型
             */
            
            let dict  = JSON as! NSDictionary
            
            //print("statuses=\(dict["statuses"]!)")
            
            if let statuses = dict["statuses"] as? [[String: AnyObject]] {
               
                let models = HomeViewModel.dict2model(array: statuses)
                
                // 缓存首页配图
                cachesHomeModelimages(list: models, finshed: finshed)
            }
            
        }) { (_, error) in
            
            finshed(nil, error)
        }
    }
    
    // MARK: 缓存首页配图
    class func cachesHomeModelimages(list: [HomeViewModel] ,finshed: @escaping (_ models:[HomeViewModel]?,_ error:Error?)->()) {
    
        // 1.创建一个组
        let group = DispatchGroup()
       
        var number:Int = 0
        
        for homeModel in list {
            
           // 1.1.判断当前微博是否有配图
//            if homeModel.storedPic_urls == nil
//            {
//                continue
//            }
            
            // 1.2. guard 是swift2.0新的判断方式
            guard homeModel.pictureURLS != nil else{
                
                continue
            }
        
            for url in homeModel.pictureURLS! {
            
                print("缓存的图片1=\(url)")
                
                // 2.将当前下载的操作加入到组中
                group.enter()
                SDWebImageManager.shared().imageDownloader?.downloadImage(with: url as URL, options: SDWebImageDownloaderOptions.lowPriority, progress: nil, completed: { (_, _, _, _) in
                    
                    number = number+1
                    // 3.离开当前组
                    group.leave()
                })
            }
        }
        
        // 4.当下载完成进行通知
        group.notify(queue: DispatchQueue.main, execute: {
            
            print("下载成功的图片数量==\(number)")
            print("图片缓存的路径=\(String.cacheDir())")
            finshed(list, nil)
            
        })
    }
    
    // MARK: 字典转模型的方法
    private class func dict2model(array:[[String: AnyObject]]) -> [HomeViewModel] {

        var models1 = [HomeViewModel]()
        
        for dict1 in array {
            
            models1.append(HomeViewModel(dict: dict1))
            
        }
        return models1
    }
    
    // 字典转模型
    init(dict: [String: AnyObject]){
        
        super.init()
        // 会调用 setValue forKey 给每一个属性赋值
        setValuesForKeys(dict)
        
    }
    
    // setValuesForKeys 内部会调用以下方法
    override func setValue(_ value: Any?, forKey key: String) {
        
        // 1.判断当前是否正在给微博字典里面的user字典赋值
        if "user" == key
        {
            // 2.根据user key 对应的字典创建一个模型
            user = HomeUserModel(dict: value as! [String: AnyObject])
            return
        }
        
        if "retweeted_status" == key
        {
            retweeted_status = HomeViewModel(dict:value as! [String : AnyObject])
            return
        }
        
        // 不等于key再去调用父类
        super.setValue(value, forKey: key)
        
    }
    
    // 这句话的意思是字典转模型的时候 要一一对应的，为了防止没有的字段崩溃，那么就跳过(没有的字段会走这里的，不用做什么操作就好了)
    //    override func setValue(_ value: Any?, forKey key: String) {
    //
    //        print("找不到\(key)")
    //    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String)
    {
        //print(key)
    }
    
    // 打印当前的模型
    static let properties = ["created_at","id","text","source","pic_urls"]
    override var description: String{
        let dict = self.dictionaryWithValues(forKeys: HomeViewModel.properties)
        return "\(dict)"
    }
}
